package com.ruike.alisurface.ui.answerQuestion;

import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.ui.answerQuestion.http.SuZhouMingYaHttp;
import com.ruike.alisurface.utils.GlideImageLoader;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.ZXingUtils;
import com.voodoo.lib_utils.FileUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;
import com.voodoo.lib_utils.imageLoader.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Arrays;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

import static com.ruike.alisurface.Constant.backgroundImg;

/**
 * Author: voodoo
 * CreateDate: 2023/11/20 020上午 11:08
 * Description: 二维码界面
 */
public class QrCodeActivity extends BaseAty {

    @BindView(R.id.qrCode_bg_imgv)
    ImageView backgroundImgv;
    @BindView(R.id.qrCode_goBack_imgv)
    ImageView goBackImgv;
    @BindView(R.id.qrCode_qrcode_img)
    ImageView qrCodeImg;
    @BindView(R.id.qrCode_countdownTime_tv)
    TextView countdownTimeTv;
    @BindView(R.id.qrCode_answerQuestion_tv)
    TextView answerQuestionTv;
    boolean isAdv;
    int oneQuestionShowTime; // 每道题展示时长

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_qr_code;
    }

    @Override
    protected void initViews() {
        isAdv = ShareUtils.getInstance().getInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_NONE) == Constant.ADV_TYPE_NONE;
        goBackImgv.setVisibility(isAdv ? View.GONE : View.VISIBLE);
        if (!isAdv) {
            startCountdownTimer(60, countdownTimeTv, null);
        }
    }

    @Override
    protected void initData() {
        oneQuestionShowTime = ShareUtils.getInstance().getInt(ShareKey.QUESTION_SHOW_TIME_KEY, 60);
    }

    @Override
    protected void onStart() {
        super.onStart();
        File[] files = FileUtils.getFolderFileList(backgroundImg);
        L.e("背景图片文件：" + (files == null ? "[]" : Arrays.toString(files)));
        if (files != null && files.length > 0) {
            String bgPath = files[0].getAbsolutePath();
            L.e("背景图片文件：" + bgPath);
            GlideImageLoader.loadImage(this, bgPath, backgroundImgv);
        }
        showProgressDialog("正在获取答题规则...");
        SuZhouMingYaHttp.getMchStrategyDescr(this);
        showProgressDialog("正在获取二维码数据...");
        SuZhouMingYaHttp.checkCanUse(this);
    }

    @OnClick({R.id.qrCode_goBack_imgv, R.id.qrCode_toLogin_view})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.qrCode_goBack_imgv:
                startCountdownTimer(0, null, null);
                break;
            case R.id.qrCode_toLogin_view:
                if (isAdv) {
                    continuousClick();
                }
                break;
        }
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
        if ("答题扫码登录成功".equals(event.type)) {
            startActivity(AnswerQuestionActivity.class, null);
            finish();
        }
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        // 检查机器是否可用，并返回二维码内容
        if (SuZhouMingYaHttp.GET_MCH_STRATEGY_DESCR_URL.equals(requestUrl)) {
            try {
                JSONObject qrCodeJSON = new JSONObject(requestJsonStr);
                JSONObject dataJson = qrCodeJSON.optJSONObject("data");
                if (dataJson != null) {
                    int questionCount = dataJson.optInt("question_count");
                    int passCount = dataJson.optInt("set_pass_count");
                    answerQuestionTv.setText(String.format(Locale.ENGLISH, getString(R.string.str_questionCount), questionCount, oneQuestionShowTime, passCount));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        // 检查机器是否可用，并返回二维码内容
        if (SuZhouMingYaHttp.CHECK_CAN_USE_URL.equals(requestUrl)) {
            String qrCodeUrlStr = "未获取到二维码内容";
            try {
                JSONObject qrCodeJSON = new JSONObject(requestJsonStr);
                JSONObject dataJson = qrCodeJSON.optJSONObject("data");
                if (dataJson != null) {
                    qrCodeUrlStr = dataJson.optString("qrcode_url");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            // 生成二维码并展示到界面上
            Bitmap qrImageBitmap = ZXingUtils.getInstance().createQRImage(qrCodeUrlStr, 300, 300, null);
            ImageLoader.loadImage(this, qrImageBitmap, qrCodeImg);
            // 然后就是等待Mqtt的回传
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
    }

}
